//
//  RCCarListInfo.m
//  CPICApp
//
//  Created by sinosoft on 13-4-12.
//  Copyright (c) 2013年 lizhiwei. All rights reserved.
//

#import "RCCarListInfo.h"
#import "Config.h"
#import "RCAlertViewUtil.h"
#import "NSString+SBJson.h"
#import "NSObject+SBJson.h"
#import "AppDelegate.h"
#import "WSqlite.h"

@implementation RCCarListInfo
@synthesize progress;
@synthesize carInfoDelegate;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

-(id)initCarListInfoView
{
    self = [super init];
    return self;
}
-(void)setCarListRequest:(BOOL)alrtCar//向太保移动平台发送请求报文
{
    //NSLog(@"userinfodefault%@",[[NSUserDefaults standardUserDefaults] objectForKey:DICT_USER_INFO]);
    alertSelectCar=alrtCar;
    NSDictionary *dictUserInfo=[[NSUserDefaults standardUserDefaults] dictionaryForKey:DICT_USER_INFO];
    if (dictUserInfo!=nil) {
        if ([dictUserInfo valueForKey:@"UserAccount"]) {
            NSLog(@"%@",[dictUserInfo valueForKey:@"UserAccount"]);
        }
    }
    else
    {
        
        //[self justShowMessage:@"用户还没登录,请登录系统" title:@"注意"];
        return;
    }
    
//    NSString *strRequestCode=@"RequestCode=61301";
    
    WSqlite *sql =[WSqlite Instance];
    arrCar=[sql getCarList:[dictUserInfo valueForKey:@"UserAccount"]];
    if ([arrCar count]>0) {
        if ([self.carInfoDelegate respondsToSelector:@selector(getCarListInfo:)]) {
            [carInfoDelegate getCarListInfo:YES];
        }
        if ([arrCar count]==1) {
            [self selectIndexCar:0];
        }
        else if([arrCar count]>1)
        {
            if (alertSelectCar==NO) //不需要弹出选择框
            {
                [self selectIndexCar:0];
            }
            else if(alertSelectCar==YES)
            {
                NSMutableDictionary *dicItemone=[arrCar objectAtIndex:0];
                NSString *strCarIDone=[dicItemone objectForKey:@"carName"];
                NSMutableDictionary *dictItemtwo=[arrCar objectAtIndex:1];
                NSString *strCarIDtwo=[dictItemtwo objectForKey:@"carName"];
                UIAlertView *myalert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"请选择对应的车牌号" delegate:self cancelButtonTitle:strCarIDone otherButtonTitles:strCarIDtwo, nil];
                myalert.tag=1001;
                [myalert show];
                [myalert release];
            }
        }
    }
    else
    {
        NSMutableDictionary *dicRequest = [NSMutableDictionary dictionary];
        [dicRequest setObject:[dictUserInfo valueForKey:@"UserAccount"] forKey:@"userAccount"];
        NSString *strRequestJson=[dicRequest JSONRepresentation];
        requestCarList = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:Server_Url_Form]];
        //设置需要POST的数据，这里提交两个数据，A=a&B=b
        [requestCarList setPostValue:@"61301" forKey:@"RequestCode"];
        [requestCarList setPostValue:strRequestJson forKey:@"RequestData"];
        
        [requestCarList setDelegate:self];
        [requestCarList setDidFailSelector:@selector(ResponseFail:)];
        [requestCarList setDidFinishSelector:@selector(ResonseSuccess:)];
        [requestCarList startAsynchronous];
        
        showProgress = YES;
        if (showProgress) {
            NSLog(@"88888");
            //[NSThread sleepForTimeInterval:1];
            progress= [[MBProgressHUD alloc]initWithView:self];
            [self addSubview:progress];
            [self bringSubviewToFront:progress];
            progress.labelText = @"查询中...";
            [progress show:YES];
            showProgress = NO;
        };
    }
    
    
}

-(void)selectIndexCar:(NSInteger)CarIndex
{
    NSDictionary *dictUserInfo1=[[NSUserDefaults standardUserDefaults] dictionaryForKey:DICT_USER_INFO];
    NSMutableDictionary *dicItem=[arrCar objectAtIndex:CarIndex];
    NSString *strCarID=[dicItem objectForKey:@"carID"];
    WSqlite *sql =[WSqlite Instance];
    NSMutableDictionary *dictCarDetail=[sql getCarDetail:strCarID withUserAccount:[dictUserInfo1 valueForKey:@"UserAccount"]];
    
    NSString *strCarNum=[dictCarDetail valueForKey:@"license"];
    NSString *strIDNum=[dictCarDetail valueForKey:@"iDNum"];
    NSString *strPolicyHolder=[dictCarDetail valueForKey:@"policyHolder"];
    NSString *strBrand=[[NSString alloc]initWithFormat:@"%@",[dictCarDetail valueForKey:@"brand"]];
    NSString *strmanufacturersName=[dictCarDetail valueForKey:@"manufacturersName"];
    NSString *strbrandName=[dictCarDetail valueForKey:@"brandName"];
    if (strCarNum.length==0) {
        strCarNum=@"";
    }
    if (strIDNum.length==0) {
        strIDNum=@"";
    }
    if (strPolicyHolder.length==0) {
        strPolicyHolder=@"";
    }
    if (strBrand.length==0) {
        strBrand=@"";
    }
    if (strmanufacturersName.length==0) {
        strmanufacturersName=@"";
    }
    if (strbrandName.length==0) {
        strbrandName=@"";
    }
    NSUserDefaults *myDefaults=[NSUserDefaults standardUserDefaults];
    NSDictionary *dictUserInfoAAA=[[NSDictionary alloc]initWithObjectsAndKeys:strCarNum,@"license",strIDNum,@"iDNum",strBrand,@"brand",strPolicyHolder,@"policyHolder",strmanufacturersName,@"manufacturersName",strbrandName,@"brandName", nil];
    [myDefaults setObject:dictUserInfoAAA forKey:DICT_CAR_CUSTOMERINFO];
    NSLog(@"DICT_CAR_CUSTOMERINFO%@",dictUserInfoAAA);
    [dictUserInfoAAA release];
    
    if ([self.carInfoDelegate respondsToSelector:@selector(getCarDetailInfo)]) {
        [self.carInfoDelegate getCarDetailInfo];
    }
}

- (void)ResonseSuccess:(ASIHTTPRequest *)request
{

    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    NSString *responseString = [request responseString];
    NSLog(@"responseString %@",responseString);
    NSMutableDictionary *dictResponse=[responseString JSONValue];
    NSLog(@"dictResponse  %@",dictResponse);
    NSMutableDictionary *dictVehicle=[dictResponse objectForKey:@"vehicleSettingInfoList"];
    arrCar=[dictVehicle objectForKey:@"data"];
    NSLog(@"%@",arrCar);
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 耗时的操作
        if ([arrCar count]>0) {
            WSqlite *sql =[WSqlite Instance];
            NSDictionary *dictUserInfo=[[NSUserDefaults standardUserDefaults] dictionaryForKey:DICT_USER_INFO];
            [sql insertCarList:arrCar withUserAccount:[dictUserInfo valueForKey:@"UserAccount"]];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            // 更新界面
        });
    });

    if ([arrCar count]>0) {
        if ([self.carInfoDelegate respondsToSelector:@selector(getCarListInfo:)]) {
            [carInfoDelegate getCarListInfo:YES];
        }
    }
    else
    {
        if ([self.carInfoDelegate respondsToSelector:@selector(getCarListInfo:)]) {
            [carInfoDelegate getCarListInfo:NO];
        }
    }
    if ([arrCar count]<=0) {
        NSUserDefaults *myDefaults=[NSUserDefaults standardUserDefaults];
        [myDefaults setObject:nil forKey:DICT_CAR_CUSTOMERINFO];
        if ([self.carInfoDelegate respondsToSelector:@selector(getCarDetailInfo)]) {
            [self.carInfoDelegate getCarDetailInfo];
        }
        return;
    }
    if ([arrCar count]==1)
    {
        NSMutableDictionary *dicItem=[arrCar objectAtIndex:0];
        NSString *strCarID=[dicItem objectForKey:@"carID"];
        if (strCarID.length!=0)
        {
            NSDictionary *dictUserInfo=[[NSUserDefaults standardUserDefaults] dictionaryForKey:DICT_USER_INFO];
            NSMutableDictionary *dicRequest = [NSMutableDictionary dictionary];
            [dicRequest setObject:strCarID forKey:@"carID"];
            [dicRequest setObject:[dictUserInfo valueForKey:@"UserAccount"] forKey:@"userAccount"];
            NSString *strRequestJson=[dicRequest JSONRepresentation];
            requestDetail = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:Server_Url_Form]];
            
            //设置需要POST的数据，这里提交两个数据，A=a&B=b
            [requestDetail setPostValue:@"61401" forKey:@"RequestCode"];
            [requestDetail setPostValue:strRequestJson forKey:@"RequestData"];
            
            [requestDetail setDelegate:self];
            [requestDetail setDidFailSelector:@selector(ResponseDetailFail:)];
            [requestDetail setDidFinishSelector:@selector(ResonseDetailSuccess:)];
            [requestDetail startAsynchronous];
            
            
            showProgress = YES;
            if (showProgress)
            {
                NSLog(@"88888");
                progress= [[MBProgressHUD alloc]initWithView:self];
                [self addSubview:progress];
                [self bringSubviewToFront:progress];
                progress.labelText = @"查询中...";
                [progress show:YES];
                showProgress = NO;
            };
        }
    }
    else if([arrCar count]>1)
    {
        if (alertSelectCar==NO) //不需要弹出选择框
        {
            NSMutableDictionary *dicItem=[arrCar objectAtIndex:0];
            NSString *strCarID=[dicItem objectForKey:@"carID"];
            if (strCarID.length!=0)
            {
                NSDictionary *dictUserInfo=[[NSUserDefaults standardUserDefaults] dictionaryForKey:DICT_USER_INFO];
                NSMutableDictionary *dicRequest = [NSMutableDictionary dictionary];
                [dicRequest setObject:strCarID forKey:@"carID"];
                [dicRequest setObject:[dictUserInfo valueForKey:@"UserAccount"] forKey:@"userAccount"];
                NSString *strRequestJson=[dicRequest JSONRepresentation];
                requestDetail = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:Server_Url_Form]];
                
                //设置需要POST的数据，这里提交两个数据，A=a&B=b
                [requestDetail setPostValue:@"61401" forKey:@"RequestCode"];
                [requestDetail setPostValue:strRequestJson forKey:@"RequestData"];
                
                [requestDetail setDelegate:self];
                [requestDetail setDidFailSelector:@selector(ResponseDetailFail:)];
                [requestDetail setDidFinishSelector:@selector(ResonseDetailSuccess:)];
                [requestDetail startAsynchronous];
                
                
                showProgress = YES;
                if (showProgress)
                {
                    NSLog(@"88888");
                    progress= [[MBProgressHUD alloc]initWithView:self];
                    [self addSubview:progress];
                    [self bringSubviewToFront:progress];
                    progress.labelText = @"查询中...";
                    [progress show:YES];
                    showProgress = NO;
                };
            }

        }
        else if(alertSelectCar==YES)
        {
            NSMutableDictionary *dicItemone=[arrCar objectAtIndex:0];
            NSString *strCarIDone=[dicItemone objectForKey:@"carName"];
            NSMutableDictionary *dictItemtwo=[arrCar objectAtIndex:1];
            NSString *strCarIDtwo=[dictItemtwo objectForKey:@"carName"];
            UIAlertView *myalert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"请选择对应的车牌号" delegate:self cancelButtonTitle:strCarIDone otherButtonTitles:strCarIDtwo, nil];
            myalert.tag=1001;
            [myalert show];
            [myalert release];
        }

    }
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag=1001) {
        if (buttonIndex==0) {
            NSMutableDictionary *dicItem=[arrCar objectAtIndex:0];
            NSString *strCarID=[dicItem objectForKey:@"carID"];
            
            NSDictionary *dictUserInfo1=[[NSUserDefaults standardUserDefaults] dictionaryForKey:DICT_USER_INFO];
            WSqlite *sql =[WSqlite Instance];
            NSMutableDictionary *dictCarDetail=[sql getCarDetail:strCarID withUserAccount:[dictUserInfo1 valueForKey:@"UserAccount"]];
            if ([dictCarDetail count]>2) {
                [self selectIndexCar:0];
            }
            else
            {
                if (strCarID.length!=0)
                {
                    NSDictionary *dictUserInfo=[[NSUserDefaults standardUserDefaults] dictionaryForKey:DICT_USER_INFO];
                    NSMutableDictionary *dicRequest = [NSMutableDictionary dictionary];
                    [dicRequest setObject:strCarID forKey:@"carID"];
                    [dicRequest setObject:[dictUserInfo valueForKey:@"UserAccount"] forKey:@"userAccount"];
                    NSString *strRequestJson=[dicRequest JSONRepresentation];
                    requestDetail = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:Server_Url_Form]];
                    
                    //设置需要POST的数据，这里提交两个数据，A=a&B=b
                    [requestDetail setPostValue:@"61401" forKey:@"RequestCode"];
                    [requestDetail setPostValue:strRequestJson forKey:@"RequestData"];
                    
                    [requestDetail setDelegate:self];
                    [requestDetail setDidFailSelector:@selector(ResponseDetailFail:)];
                    [requestDetail setDidFinishSelector:@selector(ResonseDetailSuccess:)];
                    [requestDetail startAsynchronous];
                    
                    
                    showProgress = YES;
                    if (showProgress)
                    {
                        NSLog(@"88888");
                        progress= [[MBProgressHUD alloc]initWithView:self];
                        [self addSubview:progress];
                        [self bringSubviewToFront:progress];
                        progress.labelText = @"查询中...";
                        [progress show:YES];
                        showProgress = NO;
                    };
                }
            }


        }else if(buttonIndex==1)
        {
            NSMutableDictionary *dicItem=[arrCar objectAtIndex:1];
            NSString *strCarID=[dicItem objectForKey:@"carID"];
            
            NSDictionary *dictUserInfo1=[[NSUserDefaults standardUserDefaults] dictionaryForKey:DICT_USER_INFO];
            WSqlite *sql =[WSqlite Instance];
            NSMutableDictionary *dictCarDetail=[sql getCarDetail:strCarID withUserAccount:[dictUserInfo1 valueForKey:@"UserAccount"]];
            if ([dictCarDetail count]>2) {
                [self selectIndexCar:1];
            }
            else
            {
                if (strCarID.length!=0)
                {
                    NSDictionary *dictUserInfo=[[NSUserDefaults standardUserDefaults] dictionaryForKey:DICT_USER_INFO];
                    NSMutableDictionary *dicRequest = [NSMutableDictionary dictionary];
                    [dicRequest setObject:strCarID forKey:@"carID"];
                    [dicRequest setObject:[dictUserInfo valueForKey:@"UserAccount"] forKey:@"userAccount"];
                    NSString *strRequestJson=[dicRequest JSONRepresentation];
                    requestDetail = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:Server_Url_Form]];
                    
                    //设置需要POST的数据，这里提交两个数据，A=a&B=b
                    [requestDetail setPostValue:@"61401" forKey:@"RequestCode"];
                    [requestDetail setPostValue:strRequestJson forKey:@"RequestData"];
                    
                    [requestDetail setDelegate:self];
                    [requestDetail setDidFailSelector:@selector(ResponseDetailFail:)];
                    [requestDetail setDidFinishSelector:@selector(ResonseDetailSuccess:)];
                    [requestDetail startAsynchronous];
                    
                    
                    showProgress = YES;
                    if (showProgress)
                    {
                        NSLog(@"88888");
                        progress= [[MBProgressHUD alloc]initWithView:self];
                        [self addSubview:progress];
                        [self bringSubviewToFront:progress];
                        progress.labelText = @"查询中...";
                        [progress show:YES];
                        showProgress = NO;
                    };
                }
            }

        }else
        {
            
        }
    }
}
- (void)ResonseDetailSuccess:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    NSString *responseString = [request responseString];
    NSLog(@"responseString %@",responseString);
    NSMutableDictionary *dictResponse=[responseString JSONValue];
    NSLog(@"dictResponse  %@",dictResponse);
    NSMutableDictionary *dictHead=[dictResponse valueForKey:@"head"];
    NSString *strResult= [[NSString alloc] initWithFormat:@"%@",[dictHead objectForKey:@"success"]];
    NSLog(@"strResult%@",strResult);
    if ([strResult isEqualToString:@"1"]) {
        
        NSString *strCarNum=[dictResponse valueForKey:@"license"];
        NSString *strIDNum=[dictResponse valueForKey:@"iDNum"];
        NSString *strPolicyHolder=[dictResponse valueForKey:@"policyHolder"];
        NSString *strBrand=[[NSString alloc]initWithFormat:@"%@",[dictResponse valueForKey:@"brand"]];
        NSString *strmanufacturersName=[dictResponse valueForKey:@"manufacturersName"];
        NSString *strbrandName=[dictResponse valueForKey:@"brandName"];
        if (strCarNum.length==0) {
            strCarNum=@"";
        }
        if (strIDNum.length==0) {
            strIDNum=@"";
        }
        if (strPolicyHolder.length==0) {
            strPolicyHolder=@"";
        }
        if (strBrand.length==0) {
            strBrand=@"";
        }
        if (strmanufacturersName.length==0) {
            strmanufacturersName=@"";
        }
        if (strbrandName.length==0) {
            strbrandName=@"";
        }
        NSUserDefaults *myDefaults=[NSUserDefaults standardUserDefaults];
        NSDictionary *dictUserInfo=[[NSDictionary alloc]initWithObjectsAndKeys:strCarNum,@"license",strIDNum,@"iDNum",strBrand,@"brand",strPolicyHolder,@"policyHolder",strmanufacturersName,@"manufacturersName",strbrandName,@"brandName", nil];
        [myDefaults setObject:dictUserInfo forKey:DICT_CAR_CUSTOMERINFO];
        NSLog(@"DICT_CAR_CUSTOMERINFO%@",dictUserInfo);
        [dictUserInfo release];
    }
    else
    {
    }
    [strResult release];
    if ([self.carInfoDelegate respondsToSelector:@selector(getCarDetailInfo)]) {
		[self.carInfoDelegate getCarDetailInfo];
	}
    
}

- (void)ResponseDetailFail:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    NSLog(@"服务器连接失败!");
    if ([self.carInfoDelegate respondsToSelector:@selector(getCarDetailInfo)]) {
		[self.carInfoDelegate getCarDetailInfo];
	}
}


- (void)ResponseFail:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    NSLog(@"服务器连接失败!");
    if ([self.carInfoDelegate respondsToSelector:@selector(getCarListInfo:)]) {
		[carInfoDelegate getCarListInfo:NO];
	}
    
    //[self justShowMessage:@"服务器连接失败" title:@"注意"];
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

-(void)dealloc
{
    requestCarList.delegate=nil;
    requestDetail.delegate=nil;
    [super dealloc];
}

@end
